package com.rayc.controller;

import com.rayc.config.RedisLockUtil;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class SecondKillController {

    @Autowired
    private RedisLockUtil lockUtil;

//    @Autowired
//    private CuratorFramework cf;
    //1准备商品库存
    private static Map<String,Integer> itemStock = new HashMap<>();
    //2.准备订单
    private static Map<String,Integer> itemOrder = new HashMap<>();
    static {
        itemStock.put("牙刷", 10000);
        itemOrder.put("牙刷", 0);
    }
    @GetMapping("kill")
    public String kill(String item) throws Exception {
        //开始访问共享资源，这里是访问商品信息
//        InterProcessMutex lock = new InterProcessMutex(cf,"/lock" );
        //。。。分布式 加锁
//        lock.acquire();
        //减库存
        Integer stock = itemStock.get(item);
        if(stock <= 0){
            return "没有商品了";
        }
        Thread.sleep(100);
        itemStock.put(item, stock-1);
        Thread.sleep(100);
        itemOrder.put(item, itemOrder.get(item)+1);
        //释放锁
//        lock.release();
        //将锁归还
        return "抢够成功了，"+item+"剩余："+itemStock.get(item)+",订单数--"+itemOrder.get(item);
    }


    @GetMapping("redis/kill")
    public String redisKill(String item) throws Exception {
        //。。。分布式 加锁
        if(lockUtil.lock(item, System.currentTimeMillis()+"",1 )){
            //减库存
            Integer stock = itemStock.get(item);
            if(stock <= 0){
                return "没有商品了";
            }
            Thread.sleep(100);
            itemStock.put(item, stock-1);
            Thread.sleep(100);
            itemOrder.put(item, itemOrder.get(item)+1);
            //释放锁
            lockUtil.unlock(item);
            //将锁归还
            return "抢够成功了，"+item+"剩余："+itemStock.get(item)+",订单数--"+itemOrder.get(item);
        }else{
            return "你没有抢到商品";
        }

    }
}
